/******************************************************************************/
/* File: messageQueue.cpp                                                     */
/******************************************************************************/

#include "messageQueue.h"

MessageQueue::MessageQueue() : mEvent(true) {
    
}

MessageQueue::~MessageQueue() {
    
    while(true) {
        Message *pMsg = Pop();
        if(pMsg == NULL)
            break;
        
        delete pMsg;
    }
}

int MessageQueue::PushMessage(Message *pMsg) {
    
    if(pMsg == NULL) 
        return -1;

    int r1 = Push(pMsg);
    
    if (r1 != 0) 
        return -1;
    
    int r2 = mEvent.Set();
    if (r2 != 0)
        return -1;
    
    return 0;
}

Message* MessageQueue::GetMessage() {
    
    int r = mEvent.Wait();
    if (r != 0)
        return NULL;
    
    return Pop();
}

int MessageQueue::Push(Message *pMsg) {
    
    try {
        CriticalSection cs(&mMutex);
        mMessageQueue.push(pMsg);
    } 
    catch (ThreadException te) {
        te.PrintException();
        delete pMsg;
        return -1;
    }

    return 0;
}

Message* MessageQueue::Pop() {
    
    try {
        CriticalSection cs(&mMutex);
        
        if (mMessageQueue.empty())
            return 0;
        
        Message *p = mMessageQueue.front();
        mMessageQueue.pop();
        
        return p;
    } 
    catch (ThreadException te) {
        te.PrintException();
        return NULL;
    }

}

/******************************************************************************/
/* End File: messageQueue.cpp                                                 */
/******************************************************************************/